import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'

interface Parameter {
    dom?: string | any,
    box?: Element | any,
}
interface Iworker {
    width?: string,
    height?: string,
    scale: number
}
export type UnionType = Parameter & Iworker
export class HtmlToPdf {
    dom: Parameter['dom']

    box: Parameter['box']

    width: number

    height: number

    scale: Iworker['scale']

    canvas: HTMLCanvasElement

    img: any

    imgUrl = '/'

    pdf: any = ''

    constructor(options = {
        scale: 1,
    } as UnionType) {
        // 由于需要转化的是文字
        this.dom = document.querySelector('.codecontent')
        this.box = { width: this.dom.offsetWidth, height: this.dom.offsetHeight }
        this.height = this.box.height
        this.width = this.box.width
        this.scale = options.scale
        this.canvas = document.createElement('canvas')
        this.canvas.width = this.width * this.scale
        this.canvas.height = this.height * this.scale
        this.canvas.style.width = 1900 + 'px'
        this.canvas.style.height = 1900 + 'px'
    }

    // 创建画布
    createCanvas() {
        let { canvas, scale, dom } = this
        let _this = this
        const ctx = canvas.getContext('2d')
        ctx?.scale(scale, scale)
        html2canvas(dom, {
            canvas,
            background: '#ffffff',
            dpi: 300,
        }).then(res => {
            _this.img = new Image()
            _this.imgUrl = res.toDataURL('image/jpeg', 1.0)
            _this.pdf = new jsPDF('l', 'pt', 'a4')
            _this.pdf.addImage(_this.imgUrl, 'JPEG', 10, 10, _this.img.width, _this.img.height)
            _this.img.src = _this.imgUrl
        })
        return this
    }

    // 保存为图片
    saveImg(name) {
        setTimeout(() => {
            if (this.imgUrl) {
                const linkelement = document.createElement('a')
                linkelement.setAttribute('href', this.imgUrl)
                linkelement.setAttribute('download', `${name}.jpg`)
                linkelement.click()
            }
        }, 1000)
    }

    //  另存为pdf -- 输出比较模糊
    savePdf() {
        let _this = this
        setTimeout(() => {
            if (_this.pdf) {
                //  保存PDF
                _this.pdf.save('pdf.pdf')
            }
        }, 1000)
    }

    // 转化为txt
    savetxt(data) {
        let urlObject = window.URL || window.webkitURL || window
        let export_blob = new Blob([data])
        const linkelement = document.createElement('a')
        linkelement.setAttribute('href', urlObject.createObjectURL(export_blob))
        linkelement.setAttribute('download', 'code.txt')
        linkelement.click()
    }
}
